package com.project.web.controller.sys;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.project.util.ServletContextUtil;
import com.project.web.controller.BaseController;
import com.project.entity.sys.Permissions;
import com.project.entity.sys.SysMenu;
import com.project.service.sys.MenuService;
import com.project.util.JacksonUtil;

@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController<SysMenu>{
	
	private static final Logger logger = LoggerFactory.getLogger(MenuController.class);

	@Autowired
	private MenuService menuService;
	
	@Override
	protected Class<SysMenu> getClazz() {
		// TODO Auto-generated method stub
		return SysMenu.class;
	}
	
	@RequestMapping(value="view")
	@RequiresPermissions("menu:view")
	public String view(Model model) throws IOException{
		String menuTree = menuService.queryList();
		model.addAttribute("menuTree", menuTree);
		return "/menu/view";
	}
	
	@RequestMapping(value="getMenuById")
	@ResponseBody
	public String getMenuById(Model model) throws IOException{
		SysMenu menu = getEntity();
		SysMenu m = new SysMenu();
		m.setId(menu.getId());
		m.setIcon(menu.getIcon());
		m.setName(menu.getName());
		if(menu.getPermissions()!=null){			
			Permissions p = new Permissions();
			p.setStatus(menu.getPermissions().getStatus());
			m.setPermissions(p);
		}
		m.setSort(menu.getSort());
		return JacksonUtil.objToJson(m);
	}
	
	@RequestMapping(value="update")
	@ResponseBody
	public String update(Model model,@ModelAttribute(value="entity") SysMenu entity, HttpServletRequest request)throws Exception{
		menuService.update(entity);
		List<SysMenu> firstMenu = menuService.getFirstMenu();
		ServletContextUtil.getServletContext().setAttribute("menu", firstMenu);
		return "true";
	}
}
